/*
 * Toedo
 * Copyright (C) 2009-2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package org.toedo.gui.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Shell;
import org.toedo.controllers.DataController;
import org.toedo.gui.translations.Messages;
import org.toedo.logging.Log;
import org.toedo.model.Note;
import org.toedo.model.validators.BaseNoteNameValidator;
import org.toedo.utils.Constants;

public class NewNoteAction extends Action {
	
	private Shell mShell;
	private String mTitle;
	private boolean mOpenNote;
	
	public NewNoteAction(Shell shell, boolean openNote) {
		mShell = shell;
		mTitle = null;
		mOpenNote = openNote;
	}
	
	public NewNoteAction(Shell shell, String title, boolean openNote) {
		mShell = shell;
		mTitle = title;
		mOpenNote = openNote;
	}
	
	public void run() {
		int result;
		String noteTitle;
		Note newNote = null;
		
		if ((mTitle == null) ||
				(mTitle.isEmpty())) {
			InputDialog dialog = new InputDialog(mShell, Messages.NewNoteAction_Title, Messages.NewNoteAction_Question, Constants.NOTE_DEFAULT_NAME, new BaseNoteNameValidator()); //$NON-NLS-3$

			result = dialog.open();
			noteTitle = dialog.getValue();
		} else {
			result = Dialog.OK;
			noteTitle = mTitle;
		}
		if ((result == Dialog.OK) &&
				(noteTitle != null) &&
				(!noteTitle.isEmpty())) {									
			newNote = DataController.getInstance().getProject().addNote(noteTitle);
			
			Log.getInstance(NewNoteAction.class).debug(String.format("Note created: %s (%s)", newNote.getTitle(), newNote.getId())); //$NON-NLS-1$
		}
		
		if ((mOpenNote) &&
				(newNote != null)) {
			new OpenNoteAction(newNote).run();
		}
		
	}

}
